package com.sushi.controller;

import com.sushi.pojo.Book;
import com.sushi.pojo.Option;
import com.sushi.pojo.Result;
import com.sushi.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
@CrossOrigin("*") // 允许任何(*)服务器访问
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping
    public Result findAll(){
//        try {
//            int a = 1 / 0;
//        } catch (Exception e) {
//            try {
//                throw new SystemException(Option.SYSTEM_EXCEPTION, "系统错误");
//            } catch (SystemException ex) {
//                throw new RuntimeException(ex);
//            }
//        }
        List<Book> list = bookService.findAll();
        boolean res = list.size() > 0;
        return new Result(res ? Option.SELECT_SUCCESS : Option.SELECT_FAIL, list,
                res ? "" : "查询失败");
    }
    @GetMapping("/{id}")
    public Result findById(@PathVariable int id) {
        Book book = bookService.findById(id);
        boolean res = book != null;
        return new Result(res ? Option.SELECT_SUCCESS : Option.SELECT_FAIL, book,
                res ? "" : "查询失败");
    }
    @PostMapping
    public Result save(@RequestBody Book book) {
//        System.out.println("访问到了");
        boolean res = bookService.save(book);
        return new Result(res ? Option.INSERT_SUCCESS : Option.INSERT_FAIL, null, "");
    }
    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean res = bookService.update(book);
        return new Result(res ? Option.UPDATE_SUCCESS : Option.UPDATE_FAIL, null, "");
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable int id) {
        boolean res = bookService.delete(id);
        return new Result(res ? Option.DELETE_SUCCESS : Option.DELETE_FAIL, null, "");
    }

}
